//
//  ConnectModel.m
//  ProjectForA
//
//  Created by apple on 14/11/20.
//  Copyright (c) 2014年 hmengwei. All rights reserved.
//

#import "ConnectModel.h"

@implementation ConnectModel
- (void)dealloc
{
    [_receiveData release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.receiveData = [NSMutableData data];
    }
    return self;
}

+ (void)getConnectWithUrl:(NSString *)urlstr dic:(NSMutableDictionary *)dic block:(FinishedBlock)block
{
    ConnectModel *model = [[ConnectModel alloc] init];
    model.finishBlock = block;
    [model startWithUrl:urlstr parmaters:dic];
    [model release];
}



//获取get请求地址
+ (NSString *)urlWithUrlStr:(NSString *)urlstr parmaters:(NSDictionary *)parmaters
{
    NSString *myQuery = @"";
    for (NSString *key in [parmaters allKeys]) {
        if ([myQuery length] == 0) {
            myQuery = [NSString stringWithFormat:@"?%@=%@", key, [parmaters objectForKey:key]];
        }
        myQuery = [NSString stringWithFormat:@"%@&%@=%@", myQuery, key, [parmaters objectForKey:key]];
    }
    
    urlstr = [NSString stringWithFormat:@"%@%@", urlstr, myQuery];
    return urlstr;
}

- (void)startWithUrl:(NSString *)urlstr parmaters:(NSDictionary *)parmaters
{
    urlstr = [ConnectModel urlWithUrlStr:urlstr parmaters:parmaters];
    self.urlName = [NSString stringWithFormat:@"%@", urlstr];
    
    urlstr = [urlstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.finishBlock(_receiveData);
}

@end
